package action.back;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;

import models.Upload;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import exception.JException;

import service.UploadCatalogService;
import utils.DateUtils;
import utils.EncodeUtils;
import utils.StringHelper;

public class FileAction extends DefaultAction{

	
	@Autowired
	private UploadCatalogService uploadCatalogService;
	
	private String ownerId;
	private String category;
	private String descn;
	private String userName;
	private String userId;
	private File filedata;
	private String filedataFileName;
	private String userLabel;
	private String filedataContentType;
	
	/**
	 * 下载
	 * @throws Exception
	 */
	public void download() throws Exception {
		String id = request.getParameter("id");
		Upload upload = getCommonService().getById(Upload.class, Integer.parseInt(id));
		String filePath = upload.getPath();
		String configPath = uploadCatalogService.getPath(upload.getCategory());
		String fileName = upload.getFileName();
		File file = new File(configPath + filePath);
		if(!file.exists()){
			
			throw new JException("对不起,文件已删除！");
			
		}
		
		BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
		byte[] buf = new byte[1024];
		int len = 0;

		response.reset();
		response.setContentType("application/x-msdownload"); 
		response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes(), "ISO8859-1") +"\""); 
		OutputStream out = response.getOutputStream();
		while((len = br.read(buf)) >0)
			out.write(buf,0,len);
		br.close();
		out.close();
	}
	
	/**
	 * 上传
	 * @return
	 */
	public String upload() {
		
		if (filedata != null && filedata.length() > 0) {
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			String datastr = DateUtils.formatDate(new Date(), "yyyy@MM@dd");
			
			String configPath = uploadCatalogService.getPath(category);
			String relativePath = StringHelper.split4join(datastr, "@",File.separator);
			
			String uploadPath = configPath + File.separator + relativePath;
			String ext = filedataFileName.substring(filedataFileName
					.lastIndexOf("."));
			File path = new File(uploadPath);
			if (!path.exists()) {
				path.mkdirs();
			}
			String newName = uuid + ext;
			String newPath = uploadPath + File.separator + newName;
			filedata.renameTo(new File(newPath));

			
			Upload upload = new Upload();
			upload.setUserLabel(userLabel);
			upload.setCategory(category);
			upload.setFileName(filedataFileName);
			upload.setPath(relativePath + File.separator + newName);
			upload.setDescn(EncodeUtils.urlDecode(descn));
			upload.setUploadTime(System.currentTimeMillis());
			upload.setUserId(EncodeUtils.urlDecode(userId));
			upload.setUserName(EncodeUtils.urlDecode(userName));
			upload.setOwnerId(ownerId);
			
			getCommonService().save(upload);
			
			
			String ifExtGrid = getParameter("ifExtGrid",true);
			if(StringHelper.parseBoolean(ifExtGrid)){
				JSONObject jsonObject = JSONObject.fromObject(upload);
				renderJson(jsonObject.toString());
			}
			else{
				JSONObject jsonObject = JSONObject.fromObject(upload);
				renderHtml(jsonObject.toString());
			}
			
		}

		return null;
	}
	
	/**
	 * 删除文件
	 *
	 */
	public void delete() {

		if(id!=null){
			rmUpload(id);
		}
		else if(ids!=null && ids.length>0){
			for(Integer id : ids){
				rmUpload(id);
			}
		}
		
		String ifExtGrid = getParameter("ifExtGrid",true);
		if(StringHelper.parseBoolean(ifExtGrid)){
			renderJson("");
		}
		else{
			renderHtml("");
		}
	}

	private void rmUpload(Integer id){
		Upload upload = getCommonService().getById(Upload.class, id);
		if(upload!=null){
			String configPath = uploadCatalogService.getPath(upload.getCategory());
			String filePath = upload.getPath();
			File file = new File(configPath + filePath);
			if(file.isFile()&&file.exists()){
				file.delete();
				
			}
			getCommonService().delete(upload);
			JSONObject jsonObject = JSONObject.fromObject(upload);
			renderJson(jsonObject.toString());
		}
		
	}
	
	public File getFiledata() {
		return filedata;
	}

	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}

	public String getFiledataContentType() {
		return filedataContentType;
	}

	public void setFiledataContentType(String filedataContentType) {
		this.filedataContentType = filedataContentType;
	}

	public String getFiledataFileName() {
		return filedataFileName;
	}

	public void setFiledataFileName(String filedataFileName) {
		this.filedataFileName = filedataFileName;
	}



	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}



	public String getDescn() {
		return descn;
	}

	public void setDescn(String descn) {
		this.descn = descn;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getOwnerId() {
		return ownerId;
	}

	public void setOwnerId(String ownerId) {
		this.ownerId = ownerId;
	}

	public String getUserLabel() {
		return userLabel;
	}

	public void setUserLabel(String userLabel) {
		this.userLabel = userLabel;
	}

	
	

}
